import Vue from 'vue';
import apiUrl from './apiUrl.js';

// #ifdef H5
import axios from 'axios'
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 创建axios实例
const request = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	// baseURL: 'https://zzd.nbyyjd.com.cn/Yyjd/',
	// 超时
	timeout: 40000
})

// request拦截器
request.interceptors.request.use(config => {
	//数据加密
	// let dec_data = Vue.prototype.$decrypt.doEncrypt(tempdata)
	let accessToken = Vue.prototype.$storage.getStorageSync('accessToken');
	let userid = Vue.prototype.$storage.getStorageSync('userid');
	let tempdata = config.data
	if (userid) {
		tempdata = {
			user_id: userid,
			...tempdata
		}
	}

	if (accessToken) {
		tempdata = {
			token: accessToken,
			...tempdata
		}
	}
	config.data = tempdata
	// get请求映射params参数
	if (config.method === 'get') {
		let url = config.url + '&' + Vue.prototype.$utils.tansParams(config.data);
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
	return config
}, error => {
	console.log(error)
	Promise.reject(error)
})
request.interceptors.response.use((res, error) => {
		// console.log(typeof res.data =='string' && res.data.includes(`Fatal error: Uncaught`))
		if (typeof res.data == 'string' && (res.data.includes(`<b>Notice</b>`) || res.data.includes(
			`Fatal error`))) {
			uni.showModal({
				title: "错误",
				content: res.data
			})
			return Promise.reject();
		}
		// 未设置状态码则默认成功状态
		const code = res.data.ret;
		// 获取错误信息
		const msg = res.data.data.msg;

		// 二进制数据则直接返回
		if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
			return res.data
		}
		if (code === 401) {
			Vue.prototype.$user.loginout();
			return Promise.reject(msg);
		} else if (code === 500) {

			return Promise.reject(msg)
		} else if (code === 403) {

			return Promise.reject(msg)
		} else if (code !== 200) {
			return Promise.reject(res.data.msg)
		} else {
			if (res.data.data.code && res.data.data.code !== 0) {
				return Promise.reject(msg);
			}
			return res.data.data
		}
	},
	error => {
		console.log('errorcode', error.response.status)
		let code = error.response.status;
		console.log('errorcode', code)
		if (code === 500) {
			return Promise.reject(msg)
		} else if (code === 403) {
			return Promise.reject(msg)
		} else if (code === 404) {
			return Promise.reject(msg)
		}
		return Promise.reject(error)
	}
)




// #endif


export default request;